from flask import Flask, request
from flask_restful import Api, Resource
from flask_pymongo import PyMongo

app = Flask(__name__)
app.config['MONGO_URI'] = 'mongodb://localhost:27017/flask'

api = Api(app)
mongo = PyMongo(app)


class User(Resource):
    def get(self, name):
        user = mongo.db.users.find_one({'name': name})
        if user is not None:
            user.pop('_id')
            return dict(result='success', user=user)
        return dict(result='error', message='No record found')

    def delete(self, name):
        result = mongo.db.users.delete_one({'name': name})
        count = result.deleted_count
        if count > 0:
            return dict(result='success', message='%d records deleted' % count)
        return dict(result='error', message='Failed to delete')

    def put(self, name):
        user = request.get_json()
        # 原博客写错了，已修改
        # result = mongo.db.users.replace_one({'name': 'name'}, user)
        result = mongo.db.users.replace_one({'name': name}, user)
        count = result.modified_count
        if count > 0:
            return dict(result='success', message='%d records modified' % count)
        return dict(result='error', message='Failed to modify')


class UserList(Resource):
    def get(self):
        users = mongo.db.users.find()
        user_list = []
        for user in users:
            user.pop('_id')
            user_list.append(user)
        return dict(result='success', userlist=user_list)

    def post(self):
        user = request.get_json()
        user_id = mongo.db.users.insert_one(user).inserted_id
        if user_id is not None:
            return dict(result='success', message='1 record added')
        return dict(result='error', message='Failed to insert')


api.add_resource(UserList, '/users')
api.add_resource(User, '/users/<name>')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

# http://www.bjhee.com/flask-ext5.html#%E7%BB%83%E4%B9%A0-pymongo%E7%BB%93%E5%90%88restful

# postman-body-raw-json
# http://127.0.0.1:5000/users
# {
#     "name":"juran",
#     "age":"18"
# }
